import pool from '../DB/db.js'
import sqlAPI from './sqlLite.js'
import sendAPI from '../CloudServer/send.js'
import { sendDingTalkMsgFn } from './sendDingTalkMsg.js'
import { syncFn } from './shareSave.js'
import dayjs from 'dayjs'
let timer = null
// 校验cookie时否过期
const checkCookiesFn = (row) => {
  console.log('定时任务checkCookiesFn', dayjs().format('YYYY-MM-DD HH:mm:ss'))
  const cookies = JSON.parse(row.cookies)
  sendAPI.sendFullPath({ fileId: '-11' }, cookies).then((res) => {
    // console.log('校验cookie时否过期',res.data);
    if (res.data && res.data.res_code == 0) {
      //token 未过期
      console.log('校验cookie时否过期', '未过期', dayjs().format('YYYY-MM-DD HH:mm:ss'))
      syncFn({ cookies }, null, pool)
    } else {
      console.log('校验cookie时已过期')
      sendDingTalkMsgFn({ login_name: row.login_name, isExpired: true })
    }
  })
}
function createTimedTask(login_name, result) {
  // 查询数据
  const selectSql = `SELECT * FROM users WHERE login_name = ?;`
  pool.all(selectSql, [login_name], (err, rows) => {
    if (err) {
      console.log('createTimedTask >>>', err)
      result && result.status(500).json(err)
    } else {
      const row = rows[0]
      if (row && row.is_execute == 1) {
        timer && clearInterval(timer)
        timer = setInterval(() => {
          console.log('定时任务执行中...', dayjs().format('YYYY-MM-DD HH:mm:ss'))
          checkCookiesFn(row)
        }, 1000 * 60 * row.time_interval)
        console.log('定时任务执行中...', dayjs().format('YYYY-MM-DD HH:mm:ss'))
        // checkCookiesFn(row)
        result && result.status(200).json({ res_code: 0, res_message: '定时任务已执行' })
      }
      if (row && row.is_execute == 0) {
        if (timer) {
          clearInterval(timer)
        }
      }
    }
  })
}

export default { createTimedTask }
